//
//  MoviePlayer.m
//  movie
//
//  Created by MyMac on 15/4/12.
//  Copyright (c) 2015年 MyMac. All rights reserved.
//

#import "MoviePlayer.h"
#import "playBackView.h"
#import "Device.h"
#import "SVProgressHUD.h"
@interface MoviePlayer()

@property(nonatomic,strong)UIProgressView*progressLoad;
@property(nonatomic,strong)UISlider*sliderPlay;
@property(nonatomic,strong)playBackView*playBack;
@property(nonatomic,assign)CGFloat totalTime;
@property(nonatomic,assign)CGFloat timeScale;
@property(nonatomic,strong)UIButton*backBtn;
@property(nonatomic,strong)UIView*firstView;
@property(nonatomic,strong)UISlider*volumeSlider;
@end
@implementation MoviePlayer
-(void)addPlayerInformation:(CGRect)frame
{
    //if ([super initWithFrame:frame]) {
        self.userInteractionEnabled=YES;
    
    AVPlayerLayer*player=[AVPlayerLayer playerLayerWithPlayer:self.player];
        player.contentsScale=1.0f;
        player.contentsRect=frame;
    player.frame=CGRectMake(0,0, frame.size.width, frame.size.height);
        player.videoGravity=AVLayerVideoGravityResizeAspectFill;
       
        [self.layer addSublayer:player];
    player.backgroundColor=[[UIColor blackColor] CGColor];
        UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, 47)];
        self.firstView=view;
        self.volumeSlider=[[UISlider alloc]initWithFrame:CGRectMake(20,60, frame.size.height-120, 20)];
        self.volumeSlider.alpha=0.0;
        CGAffineTransform transform=CGAffineTransformIdentity;
        self.volumeSlider.transform=CGAffineTransformRotate(transform, M_PI_2);
        self.volumeSlider.frame=CGRectMake(25,60,20,frame.size.height-120);
        self.volumeSlider.tintColor=[UIColor lightGrayColor];
        [self.volumeSlider setValue:0.5 animated:YES];
        [self.volumeSlider addTarget:self action:@selector(volumeClick) forControlEvents:UIControlEventValueChanged];
        
   
        view.backgroundColor=[UIColor lightGrayColor];
        self.backBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        self.backBtn.frame=CGRectMake(0, 0, 47, 47);
        [self.backBtn setTitle:@"返回" forState:UIControlStateNormal];
        [self.backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
        
        playBackView*backView=[[NSBundle mainBundle]loadNibNamed:@"playBackView" owner:self options:0][0];
       self.sliderPlay=backView.slider;
        self.progressLoad=backView.progress;
        backView.playBlock=^(UIButton*btn){
           // if([btn.titleLabel.text isEqualToString:@"播放"])
                if(CMTimeGetSeconds(self.player.currentTime)==CMTimeGetSeconds(self.player.currentItem.duration)){
                    [self.player seekToTime:kCMTimeZero];
                     [self.player play];
                }else{
                    if([btn.titleLabel.text isEqualToString:@"播放"]){
           [self.player pause];
                }
            else{
            [self.player play];
            
            }
        
        }
        };
        __weak MoviePlayer*p=self;
        __block AVPlayerLayer*layer=player;
        __block UIView*vv=view;
        __block playBackView*bb=backView;
            MPVolumeView*volume=[[MPVolumeView alloc]initWithFrame:CGRectMake(-1000, 0,0,0)];
  
       // volume.hidden=YES;
        [self addSubview:volume];
    
        
        backView.fullblock=^(UIButton*btn){
            if([btn.titleLabel.text isEqualToString:@"退出全屏"]){
            
            CGAffineTransform transform = CGAffineTransformIdentity;
            transform = CGAffineTransformRotate(transform, M_PI/2);
            p.transform=transform;
            p.bounds=CGRectMake(0, 0,[Device currentDeviceScreen].height, [Device currentDeviceScreen].width);
            layer.frame=CGRectMake(0, 0,[Device currentDeviceScreen].height, [Device currentDeviceScreen].width);
            vv.frame=CGRectMake(0, 0,[Device currentDeviceScreen].height,47);
            layer.contentsRect=CGRectMake(0, 0,[Device currentDeviceScreen].height, [Device currentDeviceScreen].width);
            bb.frame=CGRectMake(0,[Device currentDeviceScreen].width-47,[Device currentDeviceScreen].height, 47);
            }else{
                CGAffineTransform transform = CGAffineTransformIdentity;
                transform = CGAffineTransformRotate(transform,0);
                p.transform=transform;
               
                p.bounds=CGRectMake(0,0, frame.size.width, frame.size.height);
                layer.frame=CGRectMake(0,0, frame.size.width, frame.size.height);
                vv.frame=CGRectMake(0, 0, frame.size.width, 47);
                layer.contentsRect=CGRectMake(0, 0,[Device currentDeviceScreen].height, [Device currentDeviceScreen].width);
                bb.frame=CGRectMake(0,frame.size.height-47, frame.size.width, 47);
            
                            
            }

        };
        backView.sliderBlock=^(UISlider*slider){
        
             [self.player pause];
            CGFloat speedTime = slider.value*self.totalTime;
            
            int scale =self.timeScale;
            
            CMTime cmtime =CMTimeMake(speedTime*scale, scale);
            [self.player.currentItem seekToTime:cmtime completionHandler:^(BOOL finished) {
                [self.player play];
            }];
        
        };
        UIButton*btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 47, player.frame.size.width, player.frame.size.height-47*2)];
        btn.layer.backgroundColor=[UIColor clearColor].CGColor;
        btn.autoresizesSubviews=YES;
        btn.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
        [btn addTarget:self action:@selector(tap) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        backView.frame=CGRectMake(0,frame.size.height-47, frame.size.width, 47);
           self.playBack=backView;
        [self addSubview:backView];
        [view addSubview:self.backBtn];
        [self addSubview:view];
       
        self.sliderPlay.userInteractionEnabled=NO;
        [self addSubview:self.volumeSlider];

   // }
  //  return self;
    
  

}
-(void)tap
{
    self.firstView.alpha=1;
    self.playBack.alpha=1;
    self.volumeSlider.alpha=1.0;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self animation];
    });
    
    
    
}
-(void)animation
{
  
[UIView animateWithDuration:3.0 animations:^{
    self.firstView.alpha=0;
    self.playBack.alpha=0;
    self.volumeSlider.alpha=0;
}];
    
    
    
    
}
/**
 *  调声音
 */
-(void)volumeClick
{
   
     self.player.volume=1.0-self.volumeSlider.value;
    NSLog(@"%lf",self.player.volume);

}
-(void) backClick
  {
      self.backBlock();

  
  }
-(void)addProgressObserver{
    AVPlayerItem *playerItem=self.player.currentItem;//当前的item，即当前的视频
    
    //这里设置每秒执行一次
    
    __weak  MoviePlayer*moviePlayer=self;

    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current=CMTimeGetSeconds(time);
        float total=CMTimeGetSeconds([playerItem duration]);
       // NSLog(@"当前已经播放%.2fs.  %.2f",current,total);
        
        if (current) {
            int seconds =(long)current% 60;
            int minutes =(long)current/60 % 60;
            int hours = current/ 3600;
            moviePlayer.playBack.slider.value=(CGFloat)current/(CGFloat)total;
           
            moviePlayer.playBack.currentTime.text=[NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
          //  NSLog(@"********%lf",moviePlayer.playBack.slider.value);
        }
    }];
}


-(AVPlayer*)player
{
    if(!_player){
#warning 有用的视频地
        AVPlayerItem*playerItem;
        if (![self.playerURL containsString:@"http"]) {
            NSString*str=[[NSBundle mainBundle]pathForResource:@"00.Xcode配置路径修改" ofType:@"mp4"];
            NSURL*surl=[NSURL fileURLWithPath:str];
           playerItem=[AVPlayerItem playerItemWithURL:surl];
        }else{
         playerItem=[AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.playerURL]];//AVPlayerItem一个媒体资源管理对象，管理着媒体视频的状态，信息，一个AVPlayerItem对应一个视频资源
        
        }
       
   
        [_player replaceCurrentItemWithPlayerItem:playerItem];
     //   NSLog(@"%@",self.playerURL);
        _player=[AVPlayer playerWithPlayerItem:playerItem];
    
        [self addPlayerFinishedNotifacation];
        [self addProgressObserver];
        [self addObserverToPlayerItem:playerItem];
        
    }
    return _player;
    
}
//-(void)addPlayerInformation
//{
//    NSString*str=[[NSBundle mainBundle]pathForResource:@"vedio" ofType:@"mp4"];
//    NSURL*surl=[NSURL fileURLWithPath:str];
//    //AVPlayerItem*playerItem=[AVPlayerItem playerItemWithURL:surl];
//    AVPlayerItem*playerItem=[AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.playerURL]];//AVPlayerItem一个媒体资源管理对象，管理着媒体视频的状态，信息，一个AVPlayerItem对应一个视频资源
//    [_player replaceCurrentItemWithPlayerItem:playerItem];
//    //   NSLog(@"%@",self.playerURL);
//    _player=[AVPlayer playerWithPlayerItem:playerItem];
//    
//    [self addPlayerFinishedNotifacation];
//    [self addProgressObserver];
//    [self addObserverToPlayerItem:playerItem];
//
//
//
//
//
//}
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监控网络加载情况属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    AVPlayerItem *playerItem=object;
    if ([keyPath isEqualToString:@"status"]) {
        
        AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
        if(status==AVPlayerStatusReadyToPlay){
            [SVProgressHUD dismiss];
// AVplayer播放视频时当处于这个状态才能播放，此时才能获取到视屏信息
        //    NSLog(@"正在播放...，视频总长度:%.2f",CMTimeGetSeconds(playerItem.duration));
            self.sliderPlay.userInteractionEnabled=YES;
            int seconds =(long) CMTimeGetSeconds(playerItem.duration) % 60;
            int minutes =(long)CMTimeGetSeconds(playerItem.duration) /60 % 60;
            int hours = CMTimeGetSeconds(playerItem.duration) / 3600;
            self.totalTime=CMTimeGetSeconds(playerItem.duration);
            self.timeScale=playerItem.currentTime.timescale;
            self.playBack.totalTime.text=[NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        NSArray *array=playerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);//从哪开始缓冲的，
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);//从这个开始的缓冲点，缓冲到哪了
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
        [self.progressLoad setProgress:totalBuffer/CMTimeGetSeconds(self.player.currentItem.duration)];
        NSLog(@"共缓冲：%.2f",totalBuffer);
        //
    }
}
-(void)addPlayerFinishedNotifacation
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playerFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    //AVPlayerItem控制视频播放状态，所以通知是AVPlayerItem
    
    
    
}
-(void)playerFinished
{
    NSLog(@"视频播放完成");
    
    
}
@end
